package com.hb.trade.api.routine.config.web;

import cn.hutool.extra.servlet.ServletUtil;
import com.hb.core.pojo.center.au.dto.UserApiDTO;
import com.hb.core.util.URLUtil;
import com.hb.trade.client.center.ApiInfoRoleClient;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.fzzn.core.auth.shiro.model.ShiroProperties;
import org.fzzn.core.auth.shiro.util.ShiroUtil;
import org.fzzn.core.cache.redis.StringRedisService;
import org.fzzn.core.model.enums.MsgEnum;
import org.fzzn.core.model.msg.Message;
import org.fzzn.core.util.ResultUtil;
import org.fzzn.core.web.interceptor.BaseInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 接口验证拦截器
 *
 * @author zhaojk
 */
@Slf4j
@Setter
@Getter
@Component
public class TradeInterceptor extends BaseInterceptor {

    @Value("${hb.opera-time:1000}")
    private Integer operaTime;

    protected final StringRedisService redisService;
    protected final ApiInfoRoleClient apiRoleClient;
    protected final ShiroProperties shiroProperties;

    public TradeInterceptor(StringRedisService redisService,
                            ApiInfoRoleClient apiRoleClient,
                            ShiroProperties shiroProperties) {
        this.redisService = redisService;
        this.apiRoleClient = apiRoleClient;
        this.shiroProperties = shiroProperties;
    }

    /**
     * 方法前置处理
     *
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 返回响应
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        // 客户端IP
        String clientIP = ServletUtil.getClientIP(request);
        // 请求的接口
        String requestURI = request.getRequestURI();
        String username = ShiroUtil.getUsername() == null ? "未登录" : ShiroUtil.getUsername();
        log.info("{}({}) => {}", clientIP, username, requestURI);

        // 不需要验证的接口
        List<String> ignoreUrls = shiroProperties.getIgnoreUrls();
        for (String ignoreUrl : ignoreUrls) {
            if (URLUtil.matches(requestURI, ignoreUrl)) {
                return true;
            }
        }

        UserApiDTO dto = new UserApiDTO();
        dto.setUserId(ShiroUtil.getUserId());
        dto.setApiName(requestURI.replace("v1.0", ""));

        Message<Boolean> checkAuth = apiRoleClient.checkAuth(dto);
        if (checkAuth.isSuccess() && checkAuth.getData()) {
            return true;
        }

        try {
            response.getWriter().print(ResultUtil.msg(MsgEnum.NO_AUTHORIZATION));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler,
                           ModelAndView modelAndView) throws Exception {
        // log.info("拦截器执行, 方法后执行");
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler,
                                Exception ex) throws Exception {
        // log.info("拦截器执行, 请求处理完成执行");
    }

}
